package top.ezzz.rpc.util;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import com.google.protobuf.util.JsonFormat;

import java.util.List;
import java.util.Map;

public class GrpcMessageUtil {

    public static Map<String, Object> toMap(Message message) {
        JSONObject result = null;
        try {
            String jsonStr = JsonFormat.printer().includingDefaultValueFields().print(message);
            result = JSONUtil.parseObj(jsonStr);
        } catch (InvalidProtocolBufferException e) {
            result = new JSONObject();
        }
        return result;
    }

    public static List<Object> toList(Message message) {
        JSONArray result = null;
        try {
            String jsonStr = JsonFormat.printer().includingDefaultValueFields().print(message);
            result = JSONUtil.parseArray(jsonStr);
        } catch (InvalidProtocolBufferException e) {
            result = new JSONArray();
        }
        return result;
    }

    public static JSON toJson(Message message) {
        JSON result = null;
        try {
            String jsonStr = JsonFormat.printer().includingDefaultValueFields().print(message);
            result = JSONUtil.parse(jsonStr);
        } catch (InvalidProtocolBufferException e) {
            result = new JSONObject();
        }
        return result;
    }

    public static Message toMessage(Object map, Class<? extends Message> messageClass) {
        try {
            String json = JSONUtil.toJsonStr(map);
            Message.Builder builder = (Message.Builder) messageClass.getMethod("newBuilder").invoke(null);
            JsonFormat.parser().merge(json, builder);
            return builder.build();
        } catch (Exception e) {
            return null;
        }
    }


}
